//
//  SelectRelecationAddViewController.m
//  EducationAdminClient
//
//  Created by kwsdzjx on 16/7/22.
//  Copyright © 2016年 周佳兴. All rights reserved.
//

#import "SelectRelecationAddViewController.h"
#import "ListVCCellTwo.h"

#import "AddViewController.h"
#import "ListDetailViewController.h"
#import "MJRefresh.h"
#import "SearchView.h"
//#import "WBPopMenuModel.h"
//#import "WBPopMenuSingleton.h"

#import "SearchViewController.h"

#define kRadianToDegrees(radian) (radian*180.0)/(M_PI)
#define TABLEVIEWHEADERHEIGHT 0

#define SHOULDRELOAD @"shouldReload"

@interface SelectRelecationAddViewController ()<UIAlertViewDelegate>{
    BOOL  flag;
    UIView *vHead;
    
}
@property(nonatomic,strong)NSMutableArray           *fieldArr;
@property(nonatomic,strong)NSMutableDictionary      *deleDic;
@property(nonatomic,strong)NSMutableDictionary      *addDic;

@property(nonatomic,strong)NSMutableArray           *deleArr;
@property(nonatomic,strong)NSMutableDictionary      *ADDBTN;

@property(nonatomic,strong)NSDictionary             *currentDeleteBtnDic;

@property(nonatomic,strong)NSMutableArray           *searchArr;     // for search words arr

//@property(nonatomic,strong)SearchView *searchView;
@property(nonatomic,strong)UIImageView              *trangle2;

@property(nonatomic,strong)UIImageView              *backImg;
@property(nonatomic,strong)UIAlertView*  alert;
@property(assign,nonatomic)BOOL                     canDelete;
@property(strong, nonatomic)NSMutableArray          *btnArr;
@property(strong, nonatomic)NSMutableArray          *cnName;

@property(strong, nonatomic)NSMutableArray          *detailBtns;
@property(strong, nonatomic)NSArray                 *relationAddSelect; // the select add button to athe  a  new page


@property(assign, nonatomic)BOOL                    write;      // write succeed can take out save data


@end

static const CGFloat MJDuration = 0.5;


@implementation SelectRelecationAddViewController

static int begin = 1;
static int limit = 20;
-(void)buttonUrl{
    
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    [_searchDic removeAllObjects];
    
    //    NSString *path2= myselfSaveFile(userName(), @"listsDetail", @"listsDetail.plist");
    //
    //    NSString *path3 = [path2 stringByAppendingPathComponent:[NSString stringWithFormat:@"listFor%@%@.plist", _tableId, _pageId]];
    //    _cnName = [NSMutableArray arrayWithContentsOfFile:path3];
    _needRefush = YES;
    
    _canDelete = NO;
    
    _ADDBTN = [[NSMutableDictionary alloc]init];
    
    
    _searchArr = [[NSMutableArray alloc]init];
    
    
    _boolArr = [[NSMutableArray alloc]init];
    _deleteArr = [[NSMutableArray alloc]init];
    _deleArr = [[NSMutableArray alloc]init];
    
    _isPop = @"notPop";
    _deleDic = [[NSMutableDictionary alloc]init];
    //    [self dataRequestListW];
    [self setTitleLabelText:@"列表"];
    [self createUI];
    //*** 返回按钮
    [self createLeftNavBar];
    self.tbView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    self.tbView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self footerRefresh];
    }];
    
    flag = YES;
    
    
    
    //*** the notifications
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadListView:) name:SHOULDRELOAD object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(searchReloadData:) name:@"row" object:nil];
    //    _backImg =[[UIImageView alloc]init];
    //    [self.view addSubview:_backImg];
    //    _backImg.frame = CGRectMake(0, 40, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    _backImg.backgroundColor =[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    //    [self.view bringSubviewToFront:_searchView];
    
    _backImg.userInteractionEnabled = YES;
    
    //    [_searchView settimerView:self.view];
    //    [_searchView.bottom addTarget:self action:@selector(buttomClick:) forControlEvents:UIControlEventTouchUpInside];
    _backImg.hidden = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick)];
    [_backImg addGestureRecognizer:tap];
    
    UISwipeGestureRecognizer *swip =[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipClick:)];
    swip.direction = UISwipeGestureRecognizerDirectionUp;
    [_backImg addGestureRecognizer:swip];
    
    UISwipeGestureRecognizer *bottom_swip =[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(bottom_swipClick:)];
    bottom_swip.direction = UISwipeGestureRecognizerDirectionUp;
    //    [_searchView.bottomView addGestureRecognizer:bottom_swip];
    
    [self dataRequestWithBegining:begin andLimit:limit andIsFooter:NO];
    
    
}




- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
    // check if we're not already displaying a preview controller
    //SecViewController 是要弹出悬浮展示的ViewController
    if ([self.presentedViewController isKindOfClass:[ListDetailViewController class]]) {
        return nil;
    }
    ListVCCellTwo *cell = (ListVCCellTwo *)previewingContext.sourceView;
    
    ListDetailViewController *listDVC = [[ListDetailViewController alloc] init];
    listDVC.retureView = self;
    listDVC.cnName = _cnName;
    listDVC.buttons = _detailBtns;
    listDVC.tableId = self.tableId;
    listDVC.pageId = self.pageId;
    
    listDVC.dataDic = self.dataDic;
    listDVC.ADDBTN = _ADDBTN;
    self.isPop = @"detail";
    
    
    NSDictionary *dic= [_fieldArr objectAtIndex:cell.indexPath.row];
    listDVC.detailDic = dic;
    
    return listDVC;
    
}

-(void)searchReloadData:(NSNotification *)n{
    NSArray *arr = [n object];
    _fieldArr = [NSMutableArray arrayWithArray:arr];
    [self.tbView reloadData];
}

#pragma mark - while addSucceed or changed succeed should reload Data
-(void)reloadListView:(NSNotification *)noti{
    
    self.shouldReloadList = SHOULDRELOAD;
    
}
#pragma mark - Refresh
-(void)loadNewData{
    
    _searchDic = nil;
    //    [_searchDic removeAllObjects];
    
    [self.tbView.header beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //*** setting edit style
        
        [self setStyle];
        
        // 刷新表格
        begin = 0;
        [self dataRequestWithBegining:begin andLimit:limit andIsFooter:NO];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tbView.header endRefreshing];
    });
    
}

#pragma mark - Refresh
-(void)footerRefresh{
    [self.tbView.footer beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //*** setting edit style
        
        [self setStyle];
        
        // 刷新表格
        begin += limit;
        [self dataRequestWithBegining:begin andLimit:limit andIsFooter:YES];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tbView.footer endRefreshing];
    });
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.completeBtn!=nil&&self.completeBtn.hidden == NO)
    {
        self.completeBtn.enabled = YES;
    }
    
    [self.tbView reloadData];
    
    
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    
    if (!self.needRefush) {
        self.needRefush = !self.needRefush;
        
        return;
    }
    NSString *ft = [NSString stringWithFormat:@"%@",_fieldTIme];
    NSString *dt = [NSString stringWithFormat:@"%@",_dataTime];
    NSString *ot = [NSString stringWithFormat:@"%@",_operaTIme];
    NSString *bt = [NSString stringWithFormat:@"%@",_btnTime];
    
    
    if(![ft isEqualToString:FieldTime()]||![ot isEqualToString:Operatime()]||![bt isEqualToString:BtnTime()]||![dt isEqualToString:datatime()]||[self.shouldReloadList isEqualToString:SHOULDRELOAD]){
        
        begin = 0;
        [self dataRequestWithBegining:begin andLimit:limit andIsFooter:NO];
        saveDataTime(dt);
        saveFieldTime(ft);
        saveOperaTime(ot);
        saveBtnSetTime(bt);
    }
    else{
        if(!_write)return;
        NSString *path2= myselfSaveFile(userName(), @"lists", @"lists.plist");
        
        NSString *path3 = [path2 stringByAppendingPathComponent:[NSString stringWithFormat:@"listFor%@%@.plist", self.tableId, self.pageId]];
        
        NSDictionary *saveDic = [NSDictionary dictionaryWithContentsOfFile:path3];
        NSMutableArray *currwntDataArr = [NSMutableArray arrayWithArray:[saveDic objectForKey:@"dataList"]];
        if (currwntDataArr) {
            _fieldArr = [[NSMutableArray alloc]initWithArray:currwntDataArr];
        }
        if([saveDic valueForKey:@"pageSet"]!=nil)_cnName = [[NSMutableArray alloc]initWithArray:[[saveDic valueForKey:@"pageSet"]valueForKey:@"fieldSet"]];
        if([saveDic valueForKey:@"pageSet"])_btnArr = [[saveDic valueForKey:@"pageSet"] valueForKey:@"buttonSet"];
        
        
        [self createBoolArr];
        
        self.longSelected = NO;
        
        
        
    }
   
}


-(void)createLeftNavBar{
    UIButton *leftNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.leftBtn = leftNavBtn;
    
    if (!self.longSelected) {
        [self.leftBtn setImage:[UIImage imageNamed:@"形状1-19-拷贝-4"] forState:UIControlStateNormal];
        [self.leftBtn setTitle:@"" forState:UIControlStateNormal];
        self.leftBtn.frame = CGRectMake(0, 0, 11, 37/2);
        
    }else{
        [self.leftBtn setTitle:@"取消" forState:UIControlStateNormal];
        [self.leftBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        self.leftBtn.frame = CGRectMake(0, 0, 50, 37/2);
        
    }
    
    [self.leftBtn addTarget:self action:@selector(LeftClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:self.leftBtn];
    self.navigationItem.leftBarButtonItem = item;
    
}

#pragma mark - setRithgAndUITableViewEditStyle
-(void)setStyle{
    if (self.longSelected) {
        self.longSelected = !self.longSelected;
        [self setRightBtn];
        
        self.tbView.editing = NO;
        [self.tbView reloadData];
        
        [self createBoolArr];
        
        //*** whill deleted or exit dselete shoule remove all object in delete arr
        [self.deleArr removeAllObjects];
    }
}
-(void)LeftClick:(UIButton *)btn{
    if (self.longSelected) {
        
        //*** for set selectionstyle
        [self setStyle];
    }else{
        
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(void)dataRequestWithBegining:(int)begin andLimit:(int)limit andIsFooter:(BOOL)is{
    if(self.longSelected){
        //*** setting right and left btn for editing style
        self.longSelected = NO;
        [self setRightBtn];
        
        //*** every cell have a bool value to make sure it is edit or normal here to edit the bool arr
        [self createBoolArr];
        
        //*** whill deleted or exit dselete shoule remove all object in delete arr
        [self.deleArr removeAllObjects];
    }
    
    NSDictionary *dic = _segmentArr[(long)_currentIndex];
    self.pageId = [NSString stringWithFormat:@"%@", [dic valueForKey:@"pageId"]];
    self.tableId = [NSString stringWithFormat:@"%@", [dic valueForKey:@"tableId"]];
    //*** take out the save data path
    NSString *path2= myselfSaveFile(userName(), @"lists", @"lists.plist");
    
    NSString *path3 = [path2 stringByAppendingPathComponent:[NSString stringWithFormat:@"listFor%@%@.plist", self.tableId, self.pageId]];
    
    NSString *pathForPageSet = [path2 stringByAppendingPathComponent:[NSString stringWithFormat:@"listFor%@%@pageSet.plist", self.tableId, self.pageId]];
    
    NSDictionary *saveDic = [[NSDictionary alloc]initWithContentsOfFile:path3];
//    NSDictionary *savePageSetDic = [[NSDictionary alloc]initWithContentsOfFile:pathForPageSet];
    
    NSMutableDictionary *parmas = [[NSMutableDictionary alloc]init];
    [parmas setObject:userName() forKey:@"loginName"];
    [parmas setObject:passWord() forKey:@"password"];
    
    
    //*** wheather the tableId pageId is used
    [parmas setObject:self.pageId forKey:@"pageId"];
    [parmas setObject:self.tableId forKey:@"tableId"];
    [parmas setObject:self.mainPageId forKey:@"mainPageId"];
    [parmas setObject:self.mainTableId forKey:@"mainTableId"];

    [parmas setObject:self.mainId forKey:@"mainId"];

    //*** if have alterTime use the alterTime else use nil
//    if([saveDic valueForKey:@"alterTime"]){
//        [parmas setObject:[saveDic valueForKey:@"alterTime"] forKey:@"alterTime"];
//    }else{
//        [parmas setObject:@"" forKey:@"alterTime"];
//    }
    [parmas setObject:@"1" forKey:@"source"];
    
    
    [parmas setObject:[NSString stringWithFormat:@"%i", limit] forKey:@"limit"];
    [parmas setObject:[NSString stringWithFormat:@"%i", begin] forKey:@"start"];
    
    //    NSString *requestStr =getUrl(List_URL);
    
    if(_searchDic.count>0){
        parmas = [[NSMutableDictionary alloc]initWithDictionary:self.searchDic];
        [parmas setObject:[NSString stringWithFormat:@"%i", limit] forKey:@"limit"];
        [parmas setObject:[NSString stringWithFormat:@"%i", begin] forKey:@"start"];
        
        //        NSString *limitStr = [NSString stringWithFormat:@"%@", [self.searchDic valueForKey:@"start"]];
    }
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", self.programaUrl, LISTSVIEWREQUEST_URL];
    
    
    
    //    http://192.168.6.150:8081/edus_auto/model_interfaceToList.do?
    [NetRequest requestUrl:requestUrl andParamas:parmas andReturnBlock:^(NSData *data, NSError *error) {
        //*** saveCurrArr
        NSMutableArray *btnArr = [[NSMutableArray alloc]init];
        
        self.shouldReloadList = @"loading";
        if(data !=nil&&!error){
            
            NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            [self dataUse:obj andSaveDic:saveDic andButtonArr:btnArr andIsFooter:is andWritePath:path3 andPagePath:pathForPageSet];
            
            NSLog(@"%@",obj);
            
            //            [self createBoolArr];
            //            [self ifHaveAdd];
            
        }else{
            
            [self dataUse:saveDic andSaveDic:saveDic andButtonArr:btnArr andIsFooter:is andWritePath:path3 andPagePath:pathForPageSet];
        }
    }];
    
    
}


-(void)dataUse:(id)obj andSaveDic:(NSDictionary *)saveDic andButtonArr:(NSMutableArray *)btnArr andIsFooter:(BOOL)is andWritePath:(NSString *)path3 andPagePath:(NSString *)pagePath{
    //*** take the data to the data arr and page cN_Pl name
    NSLog(@"%@", [[[obj valueForKey:@"pageSet"]valueForKey:@"fieldSet"][0]valueForKey:@"fieldCnName"]);
    NSMutableArray *currwntDataArr = [NSMutableArray arrayWithArray:[obj objectForKey:@"dataList"]];
    if([obj valueForKey:@"pageSet"]!=nil){
        
        _cnName = [[NSMutableArray alloc]initWithArray:[[obj valueForKey:@"pageSet"]valueForKey:@"fieldSet"]];
        
    }
    if(_cnName == nil){
        if([saveDic valueForKey:@"pageSet"]!=nil)_cnName = [[NSMutableArray alloc]initWithArray:[[saveDic valueForKey:@"pageSet"]valueForKey:@"fieldSet"]];
    }
    if([obj valueForKey:@"pageSet"]){
        btnArr = [[obj valueForKey:@"pageSet"] valueForKey:@"buttonSet"];
        self.searchArr = [[obj valueForKey:@"pageSet"] valueForKey:@"serachSet"];
        //*** setting right button can use
#warning these kind of code mast cahnge rewrite
        NSMutableArray *btnArrU = [[NSMutableArray alloc]initWithArray:btnArr];
        
        for (NSDictionary *dic in btnArrU) {
            NSString *str = [NSString stringWithFormat:@"%@_%@", self.pageId, [dic valueForKey:@"buttonId"]];
            BOOL can = textButton(str);
            if (!can&&![userName() isEqualToString:@"admin"]) {
                [btnArr removeObject:dic];
            }
        }
        
        
        _btnArr = btnArr; // 列表页显示按钮
        
        //*** detail
        NSMutableArray *btnArrDetail = [[obj valueForKey:@"pageSet"] valueForKey:@"operaButtonSet"];
        
        NSMutableArray *btnArrDetailU = [[NSMutableArray alloc]initWithArray:btnArrDetail];
        for (NSDictionary *dic in btnArrDetailU) {
            NSString *str = [NSString stringWithFormat:@"%@_%@", self.pageId, [dic valueForKey:@"buttonId"]];
            BOOL can = textButton(str);
            if (!can&&![userName() isEqualToString:@"admin"]) {
                [btnArrDetail removeObject:dic];
            }
        }
        
        
        _detailBtns = btnArrDetail;
        
        if(btnArr.count>0){
            self.canDelete = YES;
        }
        
        
        _relationAddSelect = [[NSArray alloc]initWithArray:[obj valueForKey:@""]];
        //*** 添加项目按钮
        [self createRightNavBar];
    }
    
    //*** no bu r
    if(btnArr.count<=0||self.searchArr.count<=0||_detailBtns.count<=0){
        if (btnArr.count <=0) {
            btnArr = [[saveDic valueForKey:@"pageSet"]valueForKey:@"buttonSet"];
            
            NSMutableArray *btnArrU = [[NSMutableArray alloc]initWithArray:btnArr];
            
            for (NSDictionary *dic in btnArrU) {
                NSString *str = [NSString stringWithFormat:@"%@_%@", self.pageId, [dic valueForKey:@"buttonId"]];
                BOOL can = textButton(str);
                if (!can) {
                    [btnArr removeObject:btnArrU];
                }
            }
            
            
            _btnArr = btnArr;
            
        }
        
        if(_detailBtns.count<=0){
            NSMutableArray *btnArrDetail = [[saveDic valueForKey:@"pageSet"] valueForKey:@"operaButtonSet"];
            
            NSMutableArray *btnArrDetailU = [[NSMutableArray alloc]init];
            
            for (NSDictionary *dic in btnArrDetailU) {
                NSString *str = [NSString stringWithFormat:@"%@_%@", self.pageId, [dic valueForKey:@"buttonId"]];
                BOOL can = textButton(str);
                if (!can&&![userName() isEqualToString:@"admin"]) {
                    [btnArrDetail removeObject:dic];
                }
            }
            
            
            _detailBtns = btnArrDetail;
            
        }
        if(self.searchArr.count<=0){
            self.searchArr = [[saveDic valueForKey:@"pageSet"]valueForKey:@"serachSet"];
        }
        
        if(btnArr.count>0){
            self.canDelete = YES;
        }
        
        //*** 添加项目按钮
        [self createRightNavBar];
        
    }
    
    for (NSDictionary *dic in currwntDataArr) {
        
        NSArray *arrqqqqq = [dic allKeys]; // 字典 Key 自动排序
        arrqqqqq = [arrqqqqq sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
            NSComparisonResult result = [obj1 compare:obj2];
            return result==NSOrderedDescending;
        }];
        
        for (int i = 0; i < _cnName.count; i ++) { // 改变之前 什么时候用什么时候取的方式 ， 事先吧数据初步处理，将右侧对应的左侧数据保存使得取时方便
            
            NSString *rightStringSave = @"";  // 下面来找 左侧 数据 所需的 对应的 右侧数据 是否存在 &&&&&（**** 存在 即保存
            
            
            for (int j = 0; j < arrqqqqq.count; j ++) {
                
                NSString *strA = [NSString stringWithFormat:@"%@", arrqqqqq[j]];
                
                
                NSString *testStr = [NSString stringWithFormat:@"%@", [_cnName[i] valueForKey:@"fieldAliasName"]] ;
                NSLog(@"%@",testStr);
                
                
                if ([testStr isEqualToString:strA]) {
                    
                    rightStringSave = [NSString stringWithFormat:@"%@", [dic valueForKey:strA]];
                    
                    //                NSString *dicStr =[_dic objectForKey:@"fieldAliasName"];
                    NSString *lastStr = [NSString stringWithFormat:@"DIC_%@",strA];
                    
                    //&&![_dic valueForKey:strA]
                    if([[dic valueForKey:strA] isKindOfClass:[NSNumber class]]&&![dic valueForKey:strA]){
                        rightStringSave =[NSString stringWithFormat:@"%@", [dic objectForKey:lastStr]];
                    }
                    
                }
                
            }
            NSString *strKey = [NSString stringWithFormat:@"cnName_%i", i]; // 将找到的 值 由于 --- 数组 是有序的 所以 存成对应序 所需的 键
            [dic setValue:rightStringSave forKey:strKey];
            
        }
    }
    if (is) {
        for (id obj in currwntDataArr) {
            [_fieldArr addObject:obj];
        }
    }else{
        _fieldArr = [NSMutableArray arrayWithArray:currwntDataArr];
    }
    
    //*** old other write now change
    //            [_fieldArr writeToFile:path3 atomically:YES];
    
    //*** the new one write all data to a the save path for now
//    _write = [obj writeToFile:path3 atomically:YES];
    [[obj valueForKey:@"pageSet"]writeToFile:pagePath atomically:YES];
    
    //            for (int i = 0; i < _fieldArr.count; i++) {
    //                [self.boolArr addObject:@"NO"];
    //            }
    
    //*** the bool arr is for delete tap
    [self createBoolArr];
    
    self.longSelected = NO;
    
}
-(void)createBoolArr{
    if(_fieldArr != nil){
        [self.boolArr removeAllObjects];
        for (int i = 0; i < _fieldArr.count; i++) {
            [self.boolArr addObject:@"NO"];
        }
        
        self.longSelected = NO;
        [self.tbView reloadData];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return TABLEVIEWHEADERHEIGHT;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    vHead =[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 50)];
    vHead.backgroundColor =[UIColor yellowColor];
    
    
    
    
    //*** shaixuan btn
    UIButton *searchBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    
    
    
    [vHead addSubview:searchBtn];
    searchBtn.backgroundColor =[UIColor whiteColor];
    
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(vHead.mas_left);
        
        make.top.equalTo(vHead.mas_top);
        make.right.equalTo(vHead.mas_right);
        make.height.equalTo(@(86/2));
    }];
    //    [searchBtn setTitle:@"筛选" forState:UIControlStateNormal];
    [searchBtn setImage:[UIImage imageNamed:@"搜索_"] forState:UIControlStateNormal];
    [searchBtn setImage:[UIImage imageNamed:@"搜索点击状态_"] forState:UIControlStateHighlighted];
    
    [searchBtn addTarget:self action:@selector(searchClick:) forControlEvents:UIControlEventTouchUpInside];
    [searchBtn setTitleColor:[UIColor colorWithHex:0x636363] forState:UIControlStateNormal];
    searchBtn.titleLabel.font =[UIFont systemFontOfSize:15];
    
    
    
    return vHead;
    
}

-(void)allClick:(UIButton *)btn{
    begin = 0;
    [self dataRequestWithBegining:begin andLimit:limit andIsFooter:NO];
}

#pragma mark ====旋转动画======
-(CABasicAnimation *)rotation:(float)dur degree:(float)degree direction:(int)direction repeatCount:(int)repeatCount
{
    CATransform3D rotationTransform = CATransform3DMakeRotation(degree, 0, 0, direction);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
    animation.duration  =  dur;
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = repeatCount;
    animation.delegate = self;
    
    return animation;
    
}



-(void)createRightNavBar{
    
    static  UIButton *rightNavBtn;
    rightNavBtn= [[UIButton alloc]init];
    rightNavBtn.frame = CGRectMake(0, 0, 25, 25);
    [rightNavBtn addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:rightNavBtn];
    self.normalBtn = item;
    self.completeBtn = rightNavBtn;
    [self setRightBtn];
    self.navigationItem.rightBarButtonItem = self.normalBtn;
    
}

-(void)setRightBtn{
    //*** mark for sub to the svn
    if (!self.longSelected) {
        [self.completeBtn setImage:[UIImage imageNamed:@"更多操作_"] forState:UIControlStateNormal];
        [self.completeBtn setTitle:@"" forState:UIControlStateNormal];
        [self.leftBtn setImage:[UIImage imageNamed:@"形状1-19-拷贝-4"] forState:UIControlStateNormal];
        [self.leftBtn setTitle:@"" forState:UIControlStateNormal];
        self.leftBtn.frame = CGRectMake(0, 0, 11, 37/2);
        if(self.btnArr.count<=0)self.completeBtn.hidden = YES;
        self.completeBtn.frame = CGRectMake(0, 0, 42/2, 42/2);
        
        
    }else{
        self.completeBtn.hidden = NO;
        [self.completeBtn setTitle:@"删除" forState:UIControlStateNormal];
        [self.completeBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [self.leftBtn setTitle:@"取消" forState:UIControlStateNormal];
        [self.leftBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        self.leftBtn.frame = CGRectMake(0, 0, 50, 37/2);
        self.completeBtn.frame = CGRectMake(0, 0, 50, 37/2);
        
        
    }
}

-(void)rightClick:(UIButton *)btn{
    btn.enabled = NO;
    if(self.longSelected){
        if(_deleArr.count==0){
            if (CURRENTVERSION<9.0) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"注意" message:@"请选择至少一项" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alert.delegate = self;
                
                [alert show];
            }else{
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注意" message:@"请选择至少一项" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *cancelAction1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    NSLog(@"delete");
                    
                    btn.enabled = YES;
                    
                    
                }];
                
                [alertController addAction:cancelAction1];
                [self presentViewController:alertController animated:YES completion:^{
                    
                }];
                
            }
            return;
            
        }
        //
        
        if (CURRENTVERSION<9.0) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"删除学员" message:@"注意:当你点删除时,数据库中也会同步删除" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
            alert.delegate = self;
            
            [alert show];
        }else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"删除学员" message:@"注意:当你点删除时,数据库中也会同步删除" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancelAction1 = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"delete");
                self.longSelected = !self.longSelected;
                [self deleRequest:self.completeBtn];
                btn.enabled = YES;
                
                
            }];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //                [self createBoolArr];
                //                [_deleArr removeAllObjects];
                
                
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:cancelAction1];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
            self.completeBtn.enabled = YES;
            
        }
        
    }else{
        UIActionSheet *actionSheet;
        //这里添加功能判断
        if (getEnglishLanguage()) {
            actionSheet = [[UIActionSheet alloc]initWithTitle:@"More" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
        }else{
            actionSheet = [[UIActionSheet alloc]initWithTitle:@"更多操作" delegate:self cancelButtonTitle:@"返回" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
        }
        
        
        
        for(NSDictionary *dic in _btnArr){
            [actionSheet addButtonWithTitle:[dic objectForKey:@"buttonName"]];
        }
        
        
        [actionSheet showInView:self.view];
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    NSLog(@"%ld", (long)buttonIndex);
    self.completeBtn.enabled = YES;
    //    if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"添加"])[self popAc:0];
    
    
    if(buttonIndex == 0){
        return;
    }
    NSDictionary *dic = _btnArr[buttonIndex-1];
    
    _currentDeleteBtnDic = dic;
    
    if ([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"12"]) {
        //        [self editStyleBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"13"]){
        [self deleteBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"0"]){
        [self addBtnClick:dic];
        //        [self popAc:0];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"3"]){
        
        self.canDelete = YES;
        [self longPressClick];
    }
    NSLog(@"%@", _btnArr);
    
}


-(void)deleteBtnClick:(NSDictionary *)dic{
    
    if(!self.canDelete)return;
    if(self.longSelected){
        NSLog(@"a");return;
    }
    self.longSelected = !self.longSelected;
    
    [self setRightBtn];
    [self.tbView reloadData];
    
    
}

-(void)addBtnClick:(NSDictionary *)dic{
    AddViewController *addVC = [[AddViewController alloc]init];
    addVC.buttonDic = dic;
    addVC.tableId = self.tableId;
    
    [self.navigationController pushViewController:addVC animated:YES];
    
    
}
#pragma mark - PopViewAC
//-(void)popAc:(NSInteger)index{
//    if (index == 0) {
//        [self selectAdd];
//    }
//}
//
//#pragma mark - SelectAdd
//-(void)selectAdd{
//    AddViewController *addVC = [[AddViewController alloc]init];
//    NSMutableDictionary *parmas = [[NSMutableDictionary alloc]init];
//    [parmas setObject:userName() forKey:@"loginName"];
//    [parmas setObject:passWord() forKey:@"password"];
//    [parmas setObject:self.pageId forKey:@"pageId"];
//    [parmas setObject:self.tableId forKey:@"tableId"];
//    NSString *requestStr =getUrl(Button_URL);
//    [NetRequest requestUrl:requestStr andParamas:parmas andReturnBlock:^(NSData *data, NSError *error) {
//        if(data!=nil&&!error){
//            NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//            NSLog(@"%@",obj);
//            NSMutableArray *setArr = [NSMutableArray arrayWithArray:[obj objectForKey:@"phoneButtonSet"]];
//            
//            
//            self.isPop = @"add";
//            NSMutableDictionary *addBtn = [[NSMutableDictionary alloc]init];
//            for(NSDictionary *dic in setArr){
//                if([[dic objectForKey:@"phoneButtonName"]isEqualToString:@"添加"]){
//                    addBtn = [NSMutableDictionary dictionaryWithDictionary:dic];
//                }
//            }
//            NSArray *buttonarr=[addBtn allKeys];
//            NSLog(@"%lu",(unsigned long)buttonarr.count);
//            if([buttonarr count]){
//                [self.navigationController pushViewController:addVC animated:YES];
//                
//                
//                addVC.dicArr =_dataDic;
//                addVC.addDic =addBtn;
//                NSLog(@"%@",addBtn);
//            }
//            
//            
//        }else{
//            
//            NSString *str = [NSString stringWithFormat:@"%@", error.localizedDescription];
//            [self showLabelWithText:str];
//        }
//        
//    }];
//    
//    
//    
//}


#pragma mark - createUI
-(void)createUI{
    
    UIScrollView *scView = [[UIScrollView alloc]init];
    [self.view addSubview: scView];
    
    
    
//    scView.backgroundColor = [UIColor redColor];
//    seg.numberOfSegments = _relationAddSelect.count;
    NSMutableArray *arrNoTitle = [[NSMutableArray alloc]init];
    for (int i = 0; i < _segmentArr.count; i++) {
        NSDictionary *dicSeg = _segmentArr[i];
        [arrNoTitle addObject:[NSString stringWithFormat:@"%@", [dicSeg valueForKey:@"childPageName"]]];

    }
//    UISegmentedControl *seg = [[UISegmentedControl alloc]initWithItems:arrNoTitle];
//    [scView addSubview:seg];
    
    
//    seg.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见
//    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
//                                             NSForegroundColorAttributeName: [UIColor whiteColor]};
//    [seg setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
//    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
//                                               NSForegroundColorAttributeName: [UIColor lightTextColor]};
    
//    [seg setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
//    seg.backgroundColor = [UIColor redColor];
//    seg.layer.cornerRadius = 0;
//    seg.selectedSegmentIndex = 0;
//    _currentIndex = seg.selectedSegmentIndex;
//    if(_segmentArr.count<2){
//        scView.contentSize = CGSizeMake(_segmentArr.count * self.view.bounds.size.width, 0);
//        seg.frame = CGRectMake(0, 5, _segmentArr.count*self.view.bounds.size.width, 50 - 10);
//    }else if(_segmentArr.count < 5){
//        scView.contentSize = CGSizeMake(_segmentArr.count * self.view.bounds.size.width/2, 0);
//        seg.frame = CGRectMake(0, 5, _segmentArr.count*self.view.bounds.size.width/2, 50 - 10);
//    }else{
//        scView.contentSize = CGSizeMake(_segmentArr.count * self.view.bounds.size.width/4, 0);
//        seg.frame = CGRectMake(0, 5, _segmentArr.count*self.view.bounds.size.width/4, 50 - 10);
//    }
//    
//    [seg addTarget:self action:@selector(segClick:) forControlEvents:UIControlEventValueChanged];
    self.tbView = [[UITableView alloc]init];
    
    [self.view addSubview:self.tbView];
    
    //    self.tbView.editing = YES;
    //    self.longSelected = YES;
    
    self.tbView.delegate = self;
    self.tbView.dataSource = self;
    //    self.tbView.editing = YES;
    self.tbView.separatorStyle =UITableViewCellSeparatorStyleNone;
    
//    [scView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view.mas_top);
//        make.left.equalTo(self.view .mas_left);
//        make.right.equalTo(self.view.mas_right);
//        make.height.equalTo(@(50));
//    }];

//    [seg mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(scView.mas_top);
//        make.left.equalTo(self.view .mas_left);
//        make.right.equalTo(self.view.mas_right);
//        make.height.equalTo(scView.mas_height);
//    }];

    [self.tbView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view .mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom).offset(-5);
    }];
    
    self.tbView.backgroundColor = [UIColor clearColor];
    
    //    self.tbView.frame = CGRectMake(0, 0, 320, 300);
}

#pragma mark - segMentClick
-(void)segClick:(UISegmentedControl *)seg{
    _currentIndex = (NSInteger *)seg.selectedSegmentIndex;
    begin = 0;
    [self dataRequestWithBegining:begin andLimit:limit andIsFooter:NO];
}
#pragma mark - shaixuan click
-(void)searchClick:(UIButton *)btn{
    
    SearchViewController *searchVC = [[SearchViewController alloc]initWithBlock:^(NSDictionary *dic) {
        _searchDic = (NSMutableDictionary *)dic;
        
    }];
    
    
    
    searchVC.pageID = self.pageId;
    searchVC.tableID = self.tableId;
    searchVC.dataArr = self.searchArr;
    searchVC.receiveParama = self;
    
    searchVC.delegate = self;
    
    [self presentViewController:searchVC animated:YES completion:^{
        
        //*** avoid pop come back more request
        self.needRefush = NO;
    }];
    
    
    
}





-(void)deleRequest:(UIButton *)btn{
    
    NSMutableDictionary *parmas = [[NSMutableDictionary alloc]init];
    [parmas setObject:userName() forKey:@"loginName"];
    [parmas setObject:passWord() forKey:@"password"];
    [parmas setObject:self.pageId forKey:@"pageId"];
    [parmas setObject:self.tableId forKey:@"tableId"];
    [parmas setObject:@"1" forKey:@"source"];
    
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    NSString *tableStr = self.tableId;
    NSString *t_str = [NSString stringWithFormat:@"T_%@_0",tableStr];
    for(int i=0;i<_deleArr.count;i++){
        NSDictionary *dic =[_deleArr objectAtIndex:i];
        if([dic objectForKey:t_str]!=nil)[arr addObject:[dic objectForKey:t_str]];
        
    }
    
    NSLog(@"%@", _currentDeleteBtnDic);
    NSString *delIds = [arr componentsJoinedByString:@","];
    [parmas setObject:delIds forKey:@"delIds"];
    [parmas setObject:[_currentDeleteBtnDic objectForKey:@"buttonType"] forKey:@"buttonType"];
    
    
    NSString *requestStr =[NSString stringWithFormat:@"%@%@", self.programaUrl, DELETE_URL];
    
    [NetRequest requestUrl:requestStr andParamas:parmas andReturnBlock:^(NSData *data, NSError *error) {
        
        //*** whill deleted or exit dselete shoule remove all object in delete arr
        [self.deleArr removeAllObjects];
        self.tbView.editing = NO;
        [self.tbView reloadData];
        
        self.completeBtn.enabled = YES;
        [self setRightBtn];
        
        if(data!=nil&&!error){
            
            NSString *str=  [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            _alert =[[UIAlertView alloc]initWithTitle:nil message:str delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
            [_alert show];
            
            
            [_fieldArr removeObjectsInArray:_deleArr];
            [self createBoolArr];
            
            
            begin = 0;
            [self dataRequestWithBegining:begin andLimit:limit andIsFooter:NO];
            
        }else{
            NSString *str = [NSString stringWithFormat:@"%@", error.localizedDescription];
            [self showLabelWithText:str];
        }
        
    }];
    
}

-(void) performDismiss:(NSTimer *)timer
{
    [_alert dismissWithClickedButtonIndex:0 animated:NO];
}

-(void)doTime:(NSTimer *)theTimer{
    UIAlertView *alert = (UIAlertView *)[theTimer userInfo];
    [alert dismissWithClickedButtonIndex:0 animated:NO];
    alert=NULL;
    [self.tbView reloadData];
}

#pragma mark - UITableViewCellDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _fieldArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        NSLog(@"123");
    }
    static NSString *listCell = @"listCell";
    ListVCCellTwo *cell = [tableView dequeueReusableCellWithIdentifier:listCell];
    if (cell == nil) {
        cell = [[ListVCCellTwo alloc]initWithReuseIdentifier:listCell];
    }
    cell.starV.hidden = YES;
    cell.indexPath = indexPath;
    
    if (CURRENTVERSION>=9.0)
    {
        [self registerForPreviewingWithDelegate:self sourceView:cell];
        NSLog(@"3D Touch  可用!");
    }
    else
    {
        NSLog(@"3D Touch 无效");
    }
    
    cell.longSelected = self.longSelected;
    //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([self.boolArr[indexPath.row]isEqualToString:@"NO"]) {
        cell.selectedMore = NO;
        [cell setSelctButton];
    }else if([self.boolArr[indexPath.row]isEqualToString:@"YES"]){
        cell.selectedMore = YES;
        [cell setSelctButton];
    }
    NSMutableArray *arr;
    arr =[NSMutableArray arrayWithArray:_fieldArr];
    NSDictionary *dic = [arr objectAtIndex:indexPath.row];
    
    NSArray *arrqqqqq = [dic allKeys];
    arrqqqqq = [arrqqqqq sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        NSComparisonResult result = [obj1 compare:obj2];
        return result==NSOrderedDescending;
    }];
    
    //    NSInteger inter = 0;
    //*** 必须先设置 dic 因为需要先设置一些东西左侧显示 右侧的等等数据 的  操  作
    cell.dic = dic;
    cell.indexPath = indexPath;
    cell.object = self;
    cell.btnsArr = [self getButtons:_detailBtns andData:dic]; //_detailBtns;
    cell.cnName = _cnName;
    cell.quickSelector1 = @selector(quickBtnClick1:);
    cell.quickSelector2 = @selector(quickBtnClick2:);
    cell.quickSelector3 = @selector(quickBtnClick3:);
    //        cell.starNUM = 3;
    
    cell.mormalBtn.indexPath = indexPath;
    [cell.mormalBtn addTarget:self action:@selector(mroMalbtnClick:) forControlEvents:UIControlEventTouchUpInside];
//
//    if (_cnName.count>=2)cell.Label1.text = [NSString stringWithFormat:@"%@", [_cnName[1] valueForKey:@"fieldCnName"]];
//    if (_cnName.count>=3)cell.Label2.text =[NSString stringWithFormat:@"%@",  [_cnName[2] valueForKey:@"fieldCnName"]];
//    if (_cnName.count>=4)cell.Label3.text =[NSString stringWithFormat:@"%@",  [_cnName[3] valueForKey:@"fieldCnName"]];
//    if (_cnName.count>=5)cell.Label4.text =[NSString stringWithFormat:@"%@",  [_cnName[4] valueForKey:@"fieldCnName"]];
//    
//    cell.Label1R.text = @"";
//    cell.Label2R.text =@"";
//    cell.Label3R.text =@"";
//    cell.Label4R.text =@"";
//    
//    for (id IDA in arrqqqqq) {
//        NSString *strA = [NSString stringWithFormat:@"%@", IDA];
//        if(_cnName.count>=2){
//            NSString *testStr = [NSString stringWithFormat:@"%@", [_cnName[1] valueForKey:@"fieldAliasName"]] ;
//            NSLog(@"%@",testStr);
//            
//            if ([testStr isEqualToString:strA]) {
//                cell.Label1R.text = [NSString stringWithFormat:@"%@", [dic valueForKey:strA]];
//                
//                
//                //                NSString *dicStr =[dic objectForKey:@"fieldAliasName"];
//                NSString *lastStr = [NSString stringWithFormat:@"DIC_%@",strA];
//                
//                //&&![dic valueForKey:strA]
//                if([[dic valueForKey:strA] isKindOfClass:[NSNumber class]]&&![dic valueForKey:strA]){
//                    cell.Label1R.text =[NSString stringWithFormat:@"%@", [dic objectForKey:lastStr]];
//                }
//                
//            }
//        }
//        if(_cnName.count>=3){
//            if ([[NSString stringWithFormat:@"%@", [_cnName[2] valueForKey:@"fieldAliasName"]] isEqualToString:strA]) {
//                cell.Label2R.text = [NSString stringWithFormat:@"%@", [dic valueForKey:strA]];
//                
//                
//                NSString *lastStr = [NSString stringWithFormat:@"DIC_%@",strA];
//                
//                if([[dic valueForKey:strA] isKindOfClass:[NSNumber class]]&&![dic valueForKey:strA]){
//                    cell.Label2R.text =[NSString stringWithFormat:@"%@", [dic objectForKey:lastStr]];
//                    
//                    NSLog(@"%@", [dic objectForKey:lastStr]);
//                }
//                
//            }
//        }
//        
//        if(_cnName.count>=4){
//            if ([[NSString stringWithFormat:@"%@", [_cnName[3] valueForKey:@"fieldAliasName"]] isEqualToString:strA]) {
//                cell.Label3R.text = [NSString stringWithFormat:@"%@", [dic valueForKey:strA]];
//                
//                //                NSString *dicStr =[dic objectForKey:@"fieldAliasName"];
//                NSString *lastStr = [NSString stringWithFormat:@"%@",strA];
//                if([[dic valueForKey:strA] isKindOfClass:[NSNumber class]]&&![dic valueForKey:strA]){
//                    cell.Label3R.text =[NSString stringWithFormat:@"%@", [dic objectForKey:lastStr]];
//                }
//                
//            }
//        }
//        
//        if(_cnName.count>=5){
//            if ([[NSString stringWithFormat:@"%@", [_cnName[4] valueForKey:@"fieldAliasName"]] isEqualToString:strA]) {
//                cell.Label4R.text = [NSString stringWithFormat:@"%@", [dic valueForKey:strA]];
//                
//                //                NSString *dicStr =[dic objectForKey:@"fieldAliasName"];
//                NSString *lastStr = [NSString stringWithFormat:@"%@",strA];
//                if([[dic valueForKey:strA] isKindOfClass:[NSNumber class]]&&![dic valueForKey:strA]){
//                    cell.Label4R.text =[NSString stringWithFormat:@"%@", [dic objectForKey:lastStr]];
//                }
//                
//            }
//        }
//        
//    }
//    //    cell.image = [dic objectForKey:@"AFM_1"];
//    NSString * titleStr = [NSString stringWithFormat:@"%@", [dic objectForKey:arrqqqqq[0]]];
//    cell.titleLabel.text = titleStr;
//    
//    NSLog(@"%@", cell.Label2R.text);
//    
//    
//    cell.mormalBtn.indexPath = indexPath;
//    [cell.mormalBtn addTarget:self action:@selector(mroMalbtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    cell.mormalBtn.hidden = YES;
//    cell.imgLine.hidden = YES;
    return cell;
}

- (void) quickBtnClick1:(BottomBtn2 *)btn{
    [self selectBottomBtn1:btn];
}

- (void) quickBtnClick2:(BottomBtn2 *)btn{
    [self selectBottomBtn2:btn];
}

- (void) quickBtnClick3:(BottomBtn2 *)btn{
    [self selectBottomBtn3:btn];
}
-(void)selectBottomBtn1:(BottomBtn2 *)btn{
    _dataDic= [_fieldArr objectAtIndex:btn.indexPath.row];
    NSDictionary *dic = btn.dic;
    if ([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"12"]) {
        [self addBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"13"]){
        [self deleteBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"15"]){
        [self addBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"18"]){
        [self addBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"21"]){
        [self zhijiecaozuo:dic withIndex:btn.indexPath];
    }
    
}


-(void)selectBottomBtn2:(BottomBtn2 *)btn{
    _dataDic= [_fieldArr objectAtIndex:btn.indexPath.row];
    NSDictionary *dic = btn.dic;
    if ([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"12"]) {
        [self addBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"13"]){
        [self deleteBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"15"]){
        [self addBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"18"]){
        [self addBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"21"]){
        [self zhijiecaozuo:dic withIndex:btn.indexPath];
    }
    
}

-(void)selectBottomBtn3:(BottomBtn2 *)btn{
    _dataDic= [_fieldArr objectAtIndex:btn.indexPath.row];
    NSDictionary *dic = btn.dic;
    if ([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"12"]) {
        [self addBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"13"]){
        [self deleteBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"15"]){
        [self addBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"18"]){
        [self addBtnClick:dic];
    }else if([[NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]isEqualToString:@"21"]){
        [self zhijiecaozuo:dic withIndex:btn.indexPath];
    }
    
}

-(void)zhijiecaozuo:(NSDictionary *)dic withIndex:(NSIndexPath *)indexPath{
    NSDictionary *detailDic= [_fieldArr objectAtIndex:indexPath.row];
    NSString *btnType = [NSString stringWithFormat:@"%@", [dic valueForKey:@"buttonType"]]; // 21 时直接操作方式
    if ([btnType containsString:@"21"]) {
        // 直接操作请求地址
        NSString *requestString = [NSString stringWithFormat:@"%@%@",BASE_URL ,STRIT];
        NSString *dataId = [NSString stringWithFormat:@"%@", [detailDic valueForKey:@"LMF_ID"]];
        NSMutableDictionary *parama = [[NSMutableDictionary alloc]init];
        [parama setObject:self.tableId forKey:@"tableId"];
        [parama setObject:self.pageId forKey:@"pageId"];
        [parama setObject:dataId forKey:@"dataIds"];
        [parama setObject:[dic valueForKey:@"directSetIds"] forKey:@"directSetIds"];
        
        [NetRequest requestUrl:requestString andParamas:parama andReturnBlock:^(NSData *data, NSError *error) {
            if (!error&&data!=nil) {
                
                NSString *ceshiStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"strit caozuo --- ceshi ---------- %@", ceshiStr);
                if (![ceshiStr isEqualToString:@"0"]) {
                    [self showLabelWithText:@"成功"];
                }else{
                    [self showLabelWithText:@"失败"];
                }
            }
        }];
        
    }
}


#pragma mark - 相关项点击事件
-(void)mroMalbtnClick:(NormalButton *)btn{
    
    
    NSDictionary *dic = [_fieldArr objectAtIndex:btn.indexPath.row];
    NSString *str = [NSString stringWithFormat:@"T_%@_0", self.tableId];
    SelectRelecationAddViewController *selcRAVC = [[SelectRelecationAddViewController alloc]init];
    selcRAVC.mainId = [dic valueForKey:str];
    selcRAVC.mainTableId = self.tableId;
    selcRAVC.mainPageId = self.pageId;
    selcRAVC.segmentArr = _relationAddSelect;
    [self.navigationController pushViewController:selcRAVC animated:YES];
}

-(void)longPressClick{
    
    if(!self.canDelete)return;
    if(self.longSelected){
        NSLog(@"a");return;
    }
    self.longSelected = !self.longSelected;
    
    [self setRightBtn];
    
    self.tbView.editing = YES;
    [self.tbView reloadData];
    
}


#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 220;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    ListVCCell *cell = (ListVCCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.selectedMore = !cell.selectedMore;
    
    if(cell.selectedMore == NO){
        [self.boolArr replaceObjectAtIndex:indexPath.row withObject:@"NO"];
        
        NSString *tableStr = self.tableId;
        NSString *t_str = [NSString stringWithFormat:@"T_%@_0",tableStr];
        
        NSDictionary *currentDic = [_fieldArr objectAtIndex:indexPath.row];
        NSString *str =[NSString stringWithFormat:@"%@", [currentDic objectForKey:t_str]];
        
        for(NSDictionary *dic in _deleArr){
            if([str isEqualToString:[NSString  stringWithFormat:@"%@", [dic objectForKey:t_str]]]){
                NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:_deleArr];
                [arr removeObject:dic];
                _deleArr = arr;
                //                    [_deleArr removeObject:dic];
            }
        }
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSLog(@"seleteCellIndex");
    if(self.longSelected){
        ListVCCell *cell = (ListVCCell *)[tableView cellForRowAtIndexPath:indexPath];
        cell.selectedMore = !cell.selectedMore;
        if(cell.selectedMore == YES){
            [self.boolArr replaceObjectAtIndex:indexPath.row withObject:@"YES"];
            NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:_deleArr];
            
            [arr addObject:[_fieldArr objectAtIndex:indexPath.row]];
            _deleArr = arr;
        }else if(cell.selectedMore == NO){
            [self.boolArr replaceObjectAtIndex:indexPath.row withObject:@"NO"];
            for(NSDictionary *dic in _deleArr){
                NSString *str =[NSString stringWithFormat:@"%@", [[_fieldArr objectAtIndex:indexPath.row]objectForKey:@"ROW_ID"]];
                if([str isEqualToString:[NSString  stringWithFormat:@"%@", [dic objectForKey:@"ROW_ID"]]]){
                    NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:_deleArr];
                    [arr removeObject:dic];
                    _deleArr = arr;
                    //                    [_deleArr removeObject:dic];
                }
            }
        }
#warning while real data come open it
        
        NSLog(@"a");return;
    }else{
        if(self.selecCell)return;
        ListDetailViewController *listDVC =[[ListDetailViewController alloc]init];
        
        listDVC.retureView = self;
        listDVC.cnName = _cnName;
        listDVC.buttons = _detailBtns;
        listDVC.tableId = self.tableId;
        listDVC.pageId = self.pageId;
        
        listDVC.dataDic = self.dataDic;
        listDVC.ADDBTN = _ADDBTN;
        self.isPop = @"detail";
        
        
        NSDictionary *dic= [_fieldArr objectAtIndex:indexPath.row];
        listDVC.detailDic = dic;
        self.selecCell = YES;
        [self.navigationController pushViewController:listDVC animated:YES];
        
    }
}


- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath{
    return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
}


-(void)netNotifation:(NSNotification *)noti{
    NSString *reqResStr = [noti object];
    if ([reqResStr isEqualToString:NETSTATE]) {
        self.completeBtn.userInteractionEnabled = YES;
    }else{
        self.completeBtn.userInteractionEnabled = NO;
    }
}





#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (CURRENTVERSION<9.0) {
        if(buttonIndex == 1){
            self.longSelected = !self.longSelected;
            [self deleRequest:self.completeBtn];
        }else if(buttonIndex == 0){
            self.completeBtn.enabled = YES;
        }
    }
    else{
        NSLog(@"%ld",(long)buttonIndex);
    }
}

/**
 * 需要传入按钮的数组，并且需要传入需要判断按钮当条的数据内容--
 */
-(NSMutableArray *)getButtons:(NSArray *)buttons andData:(NSDictionary *)detailDic{
    // 先获取权限 是否有按钮权限 由于历史问题先做的这个功能
    buttons = [ButtonsFilter textButton:self.pageId andBtnArr:buttons];
    // 再获取是否可显示
    NSArray *showButtonsArr = [[[ButtonsFilter alloc]init] listDetailButtonArrFilter:buttons andDetailDic:detailDic];
    buttons = (NSMutableArray *)showButtonsArr;
    
    return buttons;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:SHOULDRELOAD object:nil];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
